import xmltodict
import json


# xml to json
def xmlToJson(xml_str):
    try:
        json_dict = xmltodict.parse(xml_str, encoding='utf-8')
        json_str = json.dumps(json_dict, indent=2)
        return json_str
    except:
        pass


# json to xml
def jsonToXml(json_str):
    try:
        json_dict = json.loads(json_str)
        xml_str = xmltodict.unparse(json_dict, encoding='utf-8')
    except:
        xml_str = xmltodict.umparse({'request': json_dict}, encoding='utf-8')
    finally:
        return xml_str


# load xml file
def load_json(xml_path):
    # 获取xml文件
    xml_file = open(xml_path, 'r')
    xml_str = xml_file.read()
    # 将读取的xml字符串转换为字典
    json_dict = xmltodict.parse(xml_str)
    # 将字典转换为json格式的字符串
    json_str = json.dumps(json_dict, indent=2)
    # json_str = json.dumps(json_dict)
    # with open("D://config/record.json", "w") as f:
    #     json.dump(json_str, f)
    #     print("加载入文件完成...")

    return json_str


# ss = load_json('D:\est.xml');
ss = load_json('D:\MVI_63544.xml');
print(ss)
